from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from models import Blog
from database import SessionLocal, engine

app = FastAPI()

# 创建数据库表（如果不存在）
# Blog.metadata.create_all(bind=engine)

# 数据库依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/blogs")
async def get_blogs(db: Session = Depends(get_db)):
    try:
        blogs = db.query(Blog).limit(10).all()
        return {"data": blogs}
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)